package com.small.act.old;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MapActivity;
import com.small.R;
import com.small.act.discount.FavDiscountActivity;
import com.small.commom.Common;
import com.small.commom.HttpUtil;
import com.small.commom.Result;
import com.small.db.DBOpenHelper;
import com.small.model.DzModel;
import com.small.model.TypeModel;
import com.small.view.LoadingDailog;
import com.small.view.listviewimage.ItemAdapter;

public class DzHomeActivity_old extends MapActivity implements AdapterView.OnItemClickListener{

	LoadingDailog dialog;
	String dialogMsg,toastMsg;
	ListView list_view;
	ItemAdapter list_ada;
	EditText txt_find;
	ImageButton btn_find,btn_home,bottom_my,bottom_gps,bottom_mysc,bottom_add;
	LinearLayout layout_gps;
	Button btn_juli,btn_type,btn_byme;
	//定位
	BMapManager mBMapMan = null;
    LocationListener mLocationListener = null;
    static DzHomeActivity_old baiduMapActivity;
    GeoPoint pt=null;
    
    List<TypeModel> type_list;//商圈列表
    String qsID="",qsName="";//商圈ID
    int intPage=1,intPageSize=15,intOrderType=1,intJuli=500,intFindType=1;
//    1按距离( lng=??&lat=??)
//    2按热度
//    3按发布时间

	String strFindKey="";
	boolean isLoad=true;//可加载
	CharSequence[] charitem=null;
	Vector<DzModel> list_model=new Vector<DzModel>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.dz_home_old);
		onView();
		toGPS();
	}
	
	//搜索
	public void onFind(){
		dialogMsg="正在搜索...";
		han.sendEmptyMessage(0);
		new Thread(){
			public void run(){
				try {
					String result=HttpUtil.CallMethod(Common.ServerUrl+"ECardHandler.ashx?op=eCardTypeSearch&searchType=3&orderType="
							+intOrderType+"&userID=1&pageSize="+intPageSize+"&pageIndex="+intPage+"&lng="+pt.getLongitudeE6()/1e6+"&lat="+pt.getLatitudeE6()/1e6
							+"&keyword="+strFindKey);
					if(!result.equals("")){
						JSONObject json= HttpUtil.toJsonObject(result);
						if(json!=null){
							if(json.getString("resCode").equals("1")){
								Result re=HttpUtil.GetArray(json.getString("ECardTypeList"));
								if(re!=null&& re.Count()>0){
									for(int i=0; i<re.Count(); i++){
										DzModel model=new DzModel();
										model.setBigImageUrl(re.Get(i, "BigImageUrl").toString());
										model.setDistance(re.Get(i, "Distance").toString());
										model.setECardTypeID(re.Get(i, "ECardTypeID").toString());
										model.setShopAddress(re.Get(i, "ShopAddress").toString());
										model.setShopFirstName(re.Get(i, "ShopFirstName").toString());
										model.setShopID(re.Get(i, "ShopID").toString());
										model.setShopSecondName(re.Get(i, "ShopSecondName").toString());
										model.setSmallImageUrl(re.Get(i, "SmallImageUrl").toString());
										model.setValidTime(re.Get(i, "ValidTime").toString());
										model.setViewTimes(re.Get(i, "ViewTimes").toString());
										list_model.add(model);
									}
									han.sendEmptyMessage(5);
									han.sendEmptyMessage(1);
								}else{
									isLoad=false;
									toastMsg="加载结束...";
									han.sendEmptyMessage(1);
									han.sendEmptyMessage(2);
								}
							}else{
								toastMsg="搜索失败...";
								han.sendEmptyMessage(1);
								han.sendEmptyMessage(2);
							}
						}else{
							toastMsg="搜索失败...";
							han.sendEmptyMessage(1);
							han.sendEmptyMessage(2);
						}
					}else{
						toastMsg="搜索失败...";
						han.sendEmptyMessage(1);
						han.sendEmptyMessage(2);
					}
				} catch (Exception e) {
					// TODO: handle exception
					toastMsg="当前网络不可用...";
					han.sendEmptyMessage(1);
					han.sendEmptyMessage(2);
				}
			}
		}.start();
	}
	
	//商圈
	public void onData(){
		dialogMsg="加载中...";
		han.sendEmptyMessage(0);
		new Thread(){
			public void run(){
				try {
					String result=HttpUtil.CallMethod(Common.ServerUrl+"ECardHandler.ashx?op=eCardTypeSearch&searchType="+intFindType+"&orderType="+intOrderType+"&userID="
							+Common.userid+"&pageSize="+intPageSize+"&pageIndex="+intPage+"&lng="+pt.getLongitudeE6()/1e6+"&lat="+pt.getLatitudeE6()/1e6
							+"&keyword="+strFindKey);
					if(!result.equals("")){
						JSONObject json= HttpUtil.toJsonObject(result);
						if(json!=null){
							if(json.getString("resCode").equals("1")){
								Result re=HttpUtil.GetArray(json.getString("CouponList"));
								if(re!=null&& re.Count()>0){
									
								}else{
									isLoad=false;
									toastMsg="加载结束...";
									han.sendEmptyMessage(1);
									han.sendEmptyMessage(2);
								}
							}else{
								toastMsg="加载失败...";
								han.sendEmptyMessage(1);
								han.sendEmptyMessage(2);
							}
						}else{
							toastMsg="加载失败...";
							han.sendEmptyMessage(1);
							han.sendEmptyMessage(2);
						}
					}else{
						toastMsg="加载失败...";
						han.sendEmptyMessage(1);
						han.sendEmptyMessage(2);
					}
				} catch (Exception e) {
					// TODO: handle exception
					toastMsg="加载失败...";
					han.sendEmptyMessage(1);
					han.sendEmptyMessage(2);
				}
			}
		}.start();
	
	}
	
	//定位城市
    public void toGPS(){
    	toastMsg="正在查找您的位置...";
    	han.sendEmptyMessage(2);
    	baiduMapActivity=this;
    	mBMapMan = new BMapManager(getApplication());
    	mBMapMan.init(Common.BAIDU_MAP_KEY,new MyGeneralListener());
    	mBMapMan.start();
    	mLocationListener = new LocationListener(){
    		boolean isGps=true;
    		@Override
    		public void onLocationChanged(Location location) {
    			try{
    				if (location != null){
    					pt= new GeoPoint((int)(location.getLatitude()*1e6),
    						(int)(location.getLongitude()*1e6));
    					if(isGps){
    						isGps=false;
    						//onData();
    					}
    				}
    			}
    			catch (Exception e) {
    				// TODO: handle exception
    					toastMsg="定位失败...";
    					han.sendEmptyMessage(2);
    			}
    		}
    	};
    }
    
    public void ShowFindType(){
    	final CharSequence[] items = {"离我最近","人气最高","最新发布"};
        AlertDialog dlg = new AlertDialog.Builder(DzHomeActivity_old.this).setTitle("排序方式").setItems(items, new DialogInterface.OnClickListener()	            {
            public void onClick(DialogInterface dialog, int item)
            {
            	intOrderType=item+1;
            	btn_byme.setText(items[item]);
            	onData();
            }
        }).create();
		dlg.show();
    }
    //距离选择
    public void ShowFindJuli(){
    	final CharSequence[] items = {"500M","1000M","2000M","3000M"};
        AlertDialog dlg = new AlertDialog.Builder(DzHomeActivity_old.this).setTitle("请选择").setItems(items, new DialogInterface.OnClickListener()	            {
            public void onClick(DialogInterface dialog, int item)
            {
            	switch (item) {
				case 0:
					intJuli=500;
					break;
				case 1:
					intJuli=1000;
					break;
				case 2:
					intJuli=2000;
					break;
				case 3:
					intJuli=3000;
					break;
				}
            	onData();
            }
        }).create();
		dlg.show();
    }
    
    //商圈选择
    public void onFindSQ(final int i){
    	dialogMsg="载入...";
    	han.sendEmptyMessage(0);
    	new Thread(){
    		public void run(){
    			try {
    				if(i==-1){
    					DBOpenHelper dbo= new DBOpenHelper(DzHomeActivity_old.this);
        				String[] staCol={"CategoryID","CategoryName"};
        				Cursor cur=dbo.select("tbShopType", staCol, "","");
        				if(cur!=null&&cur.getCount()>0){
        					type_list=new ArrayList<TypeModel>();
        					for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
        						TypeModel model= new TypeModel();
        						model.setId(cur.getString(cur.getColumnIndex("CategoryID")));
        						model.setName(cur.getString(cur.getColumnIndex("CategoryName")));
        						type_list.add(model);
        					}
        					charitem=new CharSequence[type_list.size()];
        					for(int i =0; i<type_list.size();i++){
        						charitem[i]=type_list.get(i).getName();
        					}
        					han.sendEmptyMessage(3);
        				}else{
        					han.sendEmptyMessage(1);
        				}
    				}else{
    					DBOpenHelper dbo= new DBOpenHelper(DzHomeActivity_old.this);
        				String[] staCol={"CategoryID","CategoryName"};
        				Cursor cur=dbo.select("tbShopTypeC", staCol, "pid="+type_list.get(i).getId(),"");
        				if(cur!=null&&cur.getCount()>0){
        					type_list=new ArrayList<TypeModel>();
        					for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
        						TypeModel model= new TypeModel();
        						model.setId(cur.getString(cur.getColumnIndex("CategoryID")));
        						model.setName(cur.getString(cur.getColumnIndex("CategoryName")));
        						type_list.add(model);
        					}
        					charitem=new CharSequence[type_list.size()];
        					for(int i =0; i<type_list.size();i++){
        						charitem[i]=type_list.get(i).getName();
        					}
        					han.sendEmptyMessage(3);
        				}else{
        					qsID=type_list.get(i).getId();
        					qsName=type_list.get(i).getName();
        					han.sendEmptyMessage(4);
        				}
    				}
				} catch (Exception e) {
					// TODO: handle exception
					han.sendEmptyMessage(1);
				}
    		}
    	}.start();
    }
    
    
    public void showSq(){
    	if(type_list!=null && type_list.size()>0){
    		AlertDialog dlg = new AlertDialog.Builder(DzHomeActivity_old.this).setTitle("请选择").setItems(charitem, new DialogInterface.OnClickListener()	            {
                public void onClick(DialogInterface dialog, int item)
                {
                	onFindSQ(item);
                }
            }).create();
    		dlg.show();
    	}
    }
    
	public void onView(){
		list_view=(ListView)this.findViewById(R.id.yhqhome_list);
		list_ada=new ItemAdapter(this,list_view,list_model);
		list_view.setAdapter(list_ada);
		layout_gps=(LinearLayout)this.findViewById(R.id.yhq_gps_layout);
		txt_find=(EditText)this.findViewById(R.id.yhq_find_txt);
		
		btn_find=(ImageButton)this.findViewById(R.id.yhq_find_btn_on);
		btn_home=(ImageButton)this.findViewById(R.id.btn_home);
		btn_juli=(Button)this.findViewById(R.id.yhq_gps_juli);
		btn_type=(Button)this.findViewById(R.id.yhq_gps_type);
		btn_byme=(Button)this.findViewById(R.id.yhq_gps_byme);
		bottom_my=(ImageButton)this.findViewById(R.id.bottom_my);
		bottom_gps=(ImageButton)this.findViewById(R.id.bottom_gps);
		bottom_mysc=(ImageButton)this.findViewById(R.id.bottom_mysc);
		bottom_add=(ImageButton)this.findViewById(R.id.bottom_add);
		btn_byme.setOnClickListener(onClick);
		btn_home.setOnClickListener(onClick);
		btn_juli.setOnClickListener(onClick);
		btn_type.setOnClickListener(onClick);
		btn_find.setOnClickListener(onClick);
		bottom_my.setOnClickListener(onClick);
		bottom_gps.setOnClickListener(onClick);
		bottom_mysc.setOnClickListener(onClick);
		bottom_add.setOnClickListener(onClick);
	}
	OnClickListener onClick= new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_home:
				finish();
				break;
			case R.id.yhq_find_btn_on:
				String txtFind=txt_find.getText().toString().trim();
				if(!txtFind.equals("")){
					list_model.removeAll(list_model);
					han.sendEmptyMessage(5);
					intFindType=3;//查询方式 关键字搜索 =3
					strFindKey=txtFind;
					isLoad=true;
					onFind();
				}else{
					txt_find.setError("请输入");
				}
				break;
			case R.id.yhq_gps_juli:
				onFindSQ(-1);
				break;
			case R.id.yhq_gps_type:
				
				break;
			case R.id.yhq_gps_byme:
				ShowFindType();
				break;
			case R.id.buttom_yhxx:
				
				break;
			case R.id.bottom_gps:
				ShowFindJuli();
				break;
			case R.id.bottom_myyhq:
				Intent i = new Intent(DzHomeActivity_old.this, FavDiscountActivity.class);
				DzHomeActivity_old.this.startActivity(i);
				break;
			}
		}
	};
	Handler han= new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if(dialog!=null && dialog.isShowing()){
					dialog.UpMsg(dialogMsg);
				}else{
					dialog=new LoadingDailog(DzHomeActivity_old.this, dialogMsg);
					dialog.show();
				}
				break;
			case 1:
				if(dialog!=null){
					if(dialog.isShowing()){
						dialog.cancel();
					}
					dialog=null;
				}
				break;
			case 2:
				Toast.makeText(DzHomeActivity_old.this, toastMsg, Toast.LENGTH_SHORT).show();
				break;
			case 3:
				showSq();
				break;
			case 4:
				btn_juli.setText(qsName);
				break;
			case 5:
				list_ada.notifyDataSetChanged();
				break;
			}
		}
	};
	@Override
	protected void onDestroy()
	{
		if (mBMapMan != null)
		{
			mBMapMan.destroy();
			mBMapMan = null;
		}
		if(dialog!=null){
			if(dialog.isShowing()){
				dialog.cancel();
			}
			dialog=null;
		}
		super.onDestroy();
	}

	@Override
	protected void onPause()
	{
		mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mBMapMan.stop();
		super.onPause();
	}

	@Override
	protected void onResume()
	{
		mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
		mBMapMan.start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed()
	{
		return false;
	}
	static class MyGeneralListener implements MKGeneralListener {
        @Override
        public void onGetNetworkState(int iError) {
//            Toast.makeText(DiscountHomeActivity.baiduMapActivity.getApplicationContext(), "没有可用网络...",
//                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
              
//                Toast.makeText(DiscountHomeActivity.baiduMapActivity.getApplicationContext(), 
//                        "定位错误,请重试...",
//                        Toast.LENGTH_LONG).show();
            }
        } 
    }
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
}
